package com.example.springsecuritydemo.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
 * 登录失败处理器
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String localizedMessage = exception.getLocalizedMessage(); // 获取本地信息

        HashMap result = new HashMap();
        result.put("code",500);
        result.put("msg","登录失败"+localizedMessage); //只将异常信息返回给前端

        String json= JSON.toJSONString(result);

        //相应JSON结果，返回json数据给前端
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
